import { getImageByTaskId } from "@/api/painting";
/**
 * @description 判断图片是否是透明背景
 * @param {*} param0
 */
export async function validateIsOpacity({ filePath }) {
  let isOpacity = true;

  // 创建离屏 2D canvas 实例
  const canvas = wx.createOffscreenCanvas({
    type: "2d",
    width: 500,
    height: 500,
  });
  // 获取 context。注意这里必须要与创建时的 type 一致
  const ctx = canvas.getContext("2d");
  // 创建一个图片
  let img = canvas.createImage();
  // 等待图片加载
  img.src = filePath; // 要加载的图片 url
  return new Promise((resolve) => {
    img.onload = () => {
      canvas.width = img.width;
      canvas.height = img.height;
      const ctx = canvas.getContext("2d");
      ctx.drawImage(img, 0, 0);

      const corners = [
        { x: 0, y: 0 }, // 左上角
        { x: img.width - 1, y: 0 }, // 右上角
        { x: 0, y: img.height - 1 }, // 左下角
        { x: img.width - 1, y: img.height - 1 }, // 右下角
      ];

      let allCornersOpaque = true;
      let opacityCount = 0;
      for (const corner of corners) {
        const alpha = ctx.getImageData(corner.x, corner.y, 1, 1).data[3];
        if (alpha < 255) {
          allCornersOpaque = false;
          opacityCount = opacityCount + 1;
          break;
        }
      }

      console.log(
        allCornersOpaque ? "所有角落都是不透明的" : "至少有一个角落是透明的"
      );
      isOpacity = allCornersOpaque ? false : true;
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      resolve({
        isOpacity,
      });
    };
  });
}
export async function getImageByTask({ taskId }) {
  return new Promise(async (resolve, reject) => {
    await setTimeout(async () => {
      let res = await getImageByTaskId(taskId);
      const { state } = res.data;
      if (state == 1) {
        resolve(res);
      } else if (state != 1 && state != 4) {
        // 4是处理中
        reject(res);
      } else {
        getImageByTask({ taskId });
      }
    }, 5000);
  });
}
